package com.miracle.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;

import org.apache.log4j.Logger;

import com.miracle.cache.SyncQueue;
import com.miracle.db.DBPool;

public class DealThread implements Runnable {

	private static Logger log = Logger.getLogger(DealThread.class);

	private String name = "";

	public DealThread() {
	}

	public DealThread(String name) {
		this.name = name;
	}

	@Override
	public void run() {

		String json = SyncQueue.queue.poll();
		if (json != null) {
			log.info("josn:" + json);
			long start = System.currentTimeMillis();
			Connection conn = DBPool.getInstance().getConnection("tdlive");
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			try {
				pstmt = conn.prepareStatement("select * from channel where channelId=?");
				pstmt.setInt(1, Integer.parseInt(json));
				rs = pstmt.executeQuery();
				while (rs.next()) {
					log.info("thread," + Thread.currentThread().getName() + ":" + rs.getString("channelName"));
				}
				Thread.sleep(new Random().nextInt(4000));
			} catch (SQLException e) {
				retry(json);
				log.error(" sql exception ;", e);
			} catch (InterruptedException e) {
				retry(json);
				log.error(" interrupted; ", e);
			} finally {
				DBPool.close(pstmt, rs, conn);
			}
			long exeTime = System.currentTimeMillis() - start;
			log.info("thread," + Thread.currentThread().getName() + ":" + exeTime + "ms");
		}
	}

	private void retry(String json) {

	}

}
